<!-- eslint-disable vue/require-v-for-key -->
<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4-tag home-page">
      <!-- 工程名称 -->
      <div class="page-container">
        <Card title="工程名称" size="small">
          <span class="title-description">{{ systemInfo.ProjectName }}</span>
          <template #extra>
            <span class="card-text">工程启动时间：{{ systemInfo.ProjectStartUp }}</span>
          </template>
          <ul class="card-ul">
            <li class="color-red">
              <!-- <SettingOutlined 
                :style="{fontSize: '40px', color: '#fff'}"
                class="li-icon "/> -->
              <!-- <img class="li-icon " src="/@/assets/images/equipment.png" /> -->
              <svg
                t="1728807721129"
                class="icon li-svg"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="37792"
                width="48"
                height="48"
              >
                <path
                  d="M692.224 435.2c17.92 0 32.256-14.336 32.256-32.256v-43.008c0-17.92-14.336-32.256-32.256-32.256h-22.528c-17.92 0-36.352-11.776-40.96-26.112-4.608-14.336-12.288-59.392 0-71.68l15.872-15.872c12.8-12.8 12.8-33.28 0-46.08l-30.208-30.208c-12.288-12.8-33.28-12.8-45.568 0L552.96 153.6c-12.288 12.288-33.792 17.408-47.104 10.24-13.312-6.656-51.2-33.28-51.2-51.2v-22.528c0-17.92-14.336-32.256-32.256-32.256h-43.008c-17.92 0-32.256 14.336-32.256 32.256V112.64c0 17.92-11.776 36.352-26.112 40.96-14.336 4.608-59.392 12.288-71.68 0l-15.872-15.872c-12.8-12.8-33.28-12.8-46.08 0l-30.208 30.208c-12.8 12.8-12.8 33.28 0 45.568l15.872 15.872c12.8 12.8 17.408 33.792 10.24 47.104-6.656 13.312-33.28 51.2-51.2 51.2h-22.528c-17.92 0-32.256 14.336-32.256 32.256v43.008c0 17.92 14.336 32.256 32.256 32.256h22.528c17.92 0 36.352 11.776 40.96 26.112s12.288 59.392 0 71.68l-15.872 15.872c-12.8 12.8-12.8 33.28 0 45.568l30.208 30.72c12.8 12.288 33.28 12.288 45.568 0l15.872-15.872c12.288-12.288 33.792-17.408 46.592-10.24 13.312 6.656 51.2 33.28 51.2 51.2v22.528c0 17.92 14.336 32.256 32.256 32.256h43.008c17.92 0 32.256-14.336 32.256-32.256V650.24c0-17.92 11.776-36.352 26.112-40.96 14.336-4.608 59.392-12.288 71.68 0l15.872 15.872c12.288 12.288 33.28 12.288 45.568 0l30.208-30.208c12.8-12.8 12.8-33.28 0-46.08l-15.872-15.872c-12.288-12.288-16.896-33.792-10.24-46.592 6.656-13.312 33.28-51.2 51.2-51.2h23.552z m-291.328 86.528C323.584 521.728 261.12 458.752 261.12 381.44s62.976-140.288 140.288-140.288 140.288 62.976 140.288 140.288-62.976 140.288-140.8 140.288z m501.76 307.2c8.704 0 16.384-7.168 16.384-16.384v-21.504c0-9.216-7.168-16.384-16.384-16.384h-11.264c-9.216 0-17.92-6.144-20.48-13.312-2.048-7.168-6.144-29.696 0-35.84l7.68-7.68c6.144-6.144 6.144-16.384 0-23.04l-15.36-15.36c-6.144-6.144-16.384-6.144-22.528 0l-8.192 8.192c-6.144 6.144-16.896 8.704-23.552 5.12-6.656-3.584-25.6-16.896-25.6-25.6v-11.264c0-9.216-7.168-16.384-16.384-16.384h-21.504c-8.704 0-16.384 7.168-16.384 16.384v11.264c0 8.704-6.144 17.92-12.8 20.48-7.168 2.048-29.696 6.144-35.84 0l-7.68-8.192c-6.144-6.656-16.384-6.656-23.04 0l-15.36 15.36c-6.144 6.144-6.144 16.384 0 23.04l8.192 7.68c6.144 6.656 8.704 16.896 5.12 23.552-3.584 6.656-16.896 25.6-25.6 25.6h-11.264c-9.216 0-16.384 7.168-16.384 16.384v21.504c0 9.216 7.168 16.384 16.384 16.384h11.264c8.704 0 17.92 6.144 20.48 13.312 2.048 7.168 6.144 29.696 0 35.84L634.88 885.76c-6.144 6.656-6.144 16.896 0 23.04l15.36 15.36c6.656 6.144 16.896 6.144 23.04 0l7.68-7.68c6.656-6.656 16.896-8.704 23.552-5.12 6.656 3.584 25.088 16.896 25.088 25.6v11.264c0 9.216 7.168 16.384 16.384 16.384h21.504c9.216 0 16.384-7.168 16.384-16.384V936.96c0-8.704 6.144-17.92 13.312-20.48 7.168-2.048 29.696-6.144 35.84 0l8.192 7.68c6.144 6.144 16.384 6.144 22.528 0l15.36-15.36c6.144-6.144 6.144-16.384 0-23.04l-7.68-7.68c-6.656-6.656-8.704-16.896-5.12-23.552 3.584-6.656 16.896-25.6 25.6-25.6h10.752z m-91.648-27.136c0 29.696-24.064 53.76-53.76 53.76-30.208 0-54.272-24.064-54.272-53.76s24.064-53.76 54.272-53.76c29.696 0 53.76 24.064 53.76 53.76z"
                  p-id="37793"
                  fill="#ffffff"
                />
              </svg>
              <span class="li-text">
                <p class="potion-re">设备总数</p>
                <p class="font-32">{{ systemInfo.DevicesNumber }}</p>
              </span>
            </li>
            <li class="color-green">
              <CloudUploadOutlined :style="{ fontSize: '40px', color: '#fff' }" class="li-icon" />
              <span class="li-text">
                <p class="potion-re">在线设备数</p>
                <p class="font-32">{{ systemInfo.DevicesOnline }}</p>
              </span>
            </li>
            <li class="color-yellow">
              <ApiOutlined :style="{ fontSize: '40px', color: '#fff' }" class="li-icon" />
              <span class="li-text">
                <p class="potion-re">离线设备数</p>
                <p class="font-32">{{ systemInfo.DevicesOffline }}</p>
              </span>
            </li>
            <li class="color-blue">
              <AppstoreOutlined :style="{ fontSize: '40px', color: '#fff' }" class="li-icon" />
              <span class="li-text">
                <p class="potion-re">采集点数</p>
                <p class="font-32">{{ systemInfo.TagNumber }}</p>
              </span>
            </li>
            <li class="color-purple">
              <DashboardOutlined :style="{ fontSize: '40px', color: '#fff' }" class="li-icon" />
              <span class="li-text">
                <p class="potion-re">运行时间(min)</p>
                <p class="font-32">{{ systemInfo.ProjectRunTime }}</p>
              </span>
            </li>
          </ul>
        </Card>
      </div>
      <!-- 快捷方式 -->
      <div class="page-container">
        <Card title="快捷方式" size="small">
          <ul class="shortcuts-ul">
            <li @click="jumpRoute('设备台账')">
              <ReconciliationOutlined :style="{ fontSize: '48px', color: '#2979ff' }" />
              <p>设备台账</p>
            </li>
            <li @click="jumpRoute('设备模型')">
              <BlockOutlined :style="{ fontSize: '48px', color: '#ff9900' }" />
              <p>设备模型</p>
            </li>
            <li @click="jumpRoute('设备接入')">
              <BranchesOutlined :style="{ fontSize: '48px', color: '#19be6b' }" />
              <p>设备接入</p>
            </li>
            <li @click="jumpRoute('报警管理')">
              <ExclamationCircleFilled :style="{ fontSize: '48px', color: '#fa3534' }" />
              <p>报警管理</p>
            </li>
            <li @click="jumpRoute('实时工况')">
              <DashboardOutlined :style="{ fontSize: '48px', color: '#00CCCC' }" />
              <p>实时工况</p>
            </li>
            <li @click="jumpRoute('历史工况')">
              <LineChartOutlined :style="{ fontSize: '48px', color: '#CCCC33' }" />
              <p>历史工况</p>
            </li>
            <li @click="jumpRoute('设备卡片')">
              <IdcardFilled :style="{ fontSize: '48px', color: '#9933FF' }" />
              <p>设备卡片</p>
            </li>
            <li @click="jumpRoute('大屏设计')">
              <DesktopOutlined :style="{ fontSize: '48px', color: '#0033CC' }" />
              <p>大屏设计</p>
            </li>
          </ul>
        </Card>
      </div>
      <!-- 主机信息、系统CPU/系统内存 -->
      <div class="flex-row">
        <Card title="主机信息" size="small" class="conter-left">
          <span class="title-description">{{ systemInfo.SystemInfo }}</span>
          <ul class="echarts-list">
            <template v-for="item in hostInformation">
              <li>
                <span class="echarts-li-title">{{ item.title }}</span>
                <equipmentPie class="w-full" :loading="loadingByHost" :seriesVal="item.seriesVal" />
                <span class="echarts-li-value" v-if="item.title === 'CPU使用率'">
                  {{ item.specific }}{{ item.uinit }}
                </span>
                <span class="echarts-li-value" v-else>
                  {{ item.data[0].value }} / {{ item.data[1].total }} {{ item.uinit }}
                </span>
              </li>
            </template>
          </ul>
        </Card>
        <Card
          size="small"
          style="width: 60%"
          :tab-list="tabListNoTitle"
          :active-tab-key="noTitleKey"
          @tabChange="(key) => onTabChange(key)"
        >
          <!-- 系统CPUT -->
          <template v-if="noTitleKey === 'CPU'">
            <equipmentStackedLine
              :loading="loadingByCpu"
              :seriesVal="seriesValByCpu"
              height="430px"
            />
          </template>
          <!-- 系统内存 -->
          <template v-else>
            <equipmentStackedLine
              :loading="loadingByMemory"
              :seriesVal="seriesValByMemory"
              height="430px"
            />
          </template>
        </Card>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  import equipmentPie from '/@/views/project/home/components/equipmentPie.vue';
  import equipmentStackedLine from '/@/views/project/home/components/equipmentStackedLine.vue';
  import { Card } from 'ant-design-vue';
  import {
    SettingOutlined,
    ApiOutlined,
    AppstoreOutlined,
    CloudUploadOutlined,
    DashboardOutlined,
    ReconciliationOutlined,
    LineChartOutlined,
    BlockOutlined,
    ExclamationCircleFilled,
    BranchesOutlined,
    DesktopOutlined,
    IdcardFilled,
  } from '@ant-design/icons-vue';
  import { ref, onMounted, onBeforeUnmount, reactive } from 'vue';
  import { getiotstate, getcurrentcpu, getcurrentmemory, getsysteminfo } from '/@/api/tag/index';
  import { getiotversion } from '/@/api/server/index';
  import { useGo } from '/@/hooks/web/usePage';
  import { dateUtil } from '/@/utils/dateUtil';
  import { getObjectLocalStorage, setObjectLocalStorage } from '/@/storage/storage';

  const go = useGo();
  let loading = ref(false);
  let loadingByMemory = ref(false);
  let loadingByCpu = ref(false);
  let loadingByHost = ref(false);
  //主机信息数据
  let hostInformation = ref<any>([]);
  let systemInfo = reactive({
    ProjectName: '',
    DevicesNumber: 0,
    TagNumber: 0,
    ProjectStartUp: '',
    ProjectRunTime: 0,
    DriverAuthCount: 0,
    IotVersion: '',
    DevicesOffline: 0,
    DevicesOnline: 0,
    SystemInfo: '',
  });
  let seriesValByMemory = reactive({
    animation: false,
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
    },
    yAxis: {
      type: 'value',
      name: '单位：MB',
    },
    series: [
      {
        name: '',
        type: 'line',

        data: [],
      },
    ],
  });
  let seriesValByCpu = reactive({
    animation: false,

    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
    },
    yAxis: {
      type: 'value',
      name: '单位：%',
    },
    series: [
      {
        name: '',
        type: 'line',
        data: [],
      },
    ],
  });
  // 系统状态数据
  let dataByMemory = reactive([]);
  // 系统状态x轴数据
  let xDataByMemory = reactive([]);
  // 系统cpu x轴数据
  let xDataByCpu = reactive([]);
  // 系统cpu数据
  let dataByCpu = reactive([]);

  // 倒计时
  let timer = null;
  let timer2 = null;
  //系统CPU、系统内存
  let tabListNoTitle = reactive([
    {
      key: 'CPU',
      tab: '系统CPU',
    },
    {
      key: 'RAM',
      tab: '系统内存',
    },
  ]);
  const noTitleKey = ref('CPU');
  // 获取设备信息
  async function initData() {
    loading.value = true;
    try {
      let res = await getiotstate();
      let resByVersion = await getiotversion();
      let dataInfo = res || {};

      systemInfo.ProjectName = dataInfo.ProjectName;
      systemInfo.DevicesNumber = dataInfo.DevicesNumber;
      systemInfo.TagNumber = dataInfo.TagNumber;
      systemInfo.ProjectStartUp = dataInfo.ProjectStartUp;
      systemInfo.SystemInfo = dataInfo.SystemInfo;
      systemInfo.ProjectRunTime = systemInfo.ProjectRunTime = dataInfo.ProjectRunTimeLong;
      systemInfo.DriverAuthCount = dataInfo.DriverAuthCount;
      systemInfo.IotVersion = resByVersion;
      systemInfo.DevicesOnline = dataInfo.DevicesOnline;
      systemInfo.DevicesOffline = dataInfo.DevicesOffline;
      loading.value = false;
    } catch (err) {
      loading.value = false;
    }
  }

  //获取主机信息
  async function getSystemByHostinfor() {
    loadingByHost.value = true;
    try {
      let res = await getsysteminfo();
      let arr = Array.isArray(res) ? res : [];
      if (arr.length > 0) {
        // dataByHost = arr as never;
        arr.forEach((item) => {
          let surplus = parseFloat((item.data[1].total - item.data[0].value).toFixed(2));
          item.data.push({ value: surplus });
        });
        let _arr = arr.map((item) => {
          return {
            ...item,
            seriesVal: {
              total: item.data[1].total,
              data: item.data
                .filter((d) => d.value !== undefined) // 只保留 value 属性
                .map((d) => ({ value: d.value })), // 转换成新的对象结构
            },
          };
        });
        console.log(_arr);
        hostInformation.value = _arr as any;
      }
      loadingByHost.value = false;
    } catch (error) {
      loadingByHost.value = false;
    }
  }
  // 获取系统内存
  async function getSystemByMemory() {
    loadingByMemory.value = true;
    try {
      let res = await getcurrentmemory();
      let arr = Array.isArray(res) ? res : [];
      if (arr.length > 0) {
        xDataByMemory.push(dateUtil().format('HH:mm:ss') as never);
        dataByMemory.push(arr[0] as never);
        xDataByMemory = xDataByMemory.slice(-15);
        dataByMemory = dataByMemory.slice(-15);
        seriesValByMemory.xAxis.data = xDataByMemory;
        seriesValByMemory.series[0].data = dataByMemory;
      }
      loadingByMemory.value = false;
    } catch (error) {
      loadingByMemory.value = false;
    }
  }
  // 获取系统cpu
  async function getSystemByCpu() {
    loadingByCpu.value = true;
    try {
      let res = await getcurrentcpu();
      let arr = Array.isArray(res) ? res : [];
      if (arr.length > 0) {
        xDataByCpu.push(dateUtil().format('HH:mm:ss') as never);
        dataByCpu.push(arr[0] as never);
        xDataByCpu = xDataByCpu.slice(-15);
        dataByCpu = dataByCpu.slice(-15);
        seriesValByCpu.xAxis.data = xDataByCpu;
        seriesValByCpu.series[0].data = dataByCpu;
      }
      loadingByCpu.value = false;
    } catch (error) {
      loadingByCpu.value = false;
    }
  }
  const onTabChange = (value: string) => {
    noTitleKey.value = value;
  };
  //快捷方式
  const jumpRoute = (type: string) => {
    if (type === '设备台账') {
      go('/deviceManagement/equipmentLedger');
    }
    if (type === '设备模型') {
      go('/deviceIntegration/template');
    }
    if (type === '设备接入') {
      go('/deviceIntegration/tag');
    }
    if (type === '报警管理') {
      go('/alarmManagement/index');
    }
    if (type === '实时工况') {
      go('/ioTPresentation/eqIntegrationPage');
    }
    if (type === '历史工况') {
      go('/ioTPresentation/diagnosis');
    }
    if (type === '设备卡片') {
      go('/ioTPresentation/equipmentCard');
    }
    if (type === '大屏设计') {
      go('/rowCodeLarge/index');
    }
  };
  onMounted(async () => {
    initData();
    getSystemByHostinfor();
    let localDataByMemory = getObjectLocalStorage('localDataByMemory') || {
      xDataByMemory: [],
      dataByMemory: [],
    };
    xDataByMemory = localDataByMemory.xDataByMemory;
    dataByMemory = localDataByMemory.dataByMemory;
    let localDataByCpu = getObjectLocalStorage('localDataByCpu') || {
      xDataByCpu: [],
      dataByCpu: [],
    };
    xDataByCpu = localDataByCpu.xDataByCpu;
    dataByCpu = localDataByCpu.dataByCpu;
    getSystemByCpu();
    getSystemByMemory();
    timer = setInterval(() => {
      getSystemByMemory();
      getSystemByCpu();
      getSystemByHostinfor();
    }, 15000);
    timer2 = setInterval(() => {
      initData();
    }, 300000);
  });
  onBeforeUnmount(() => {
    // 页面销毁之前，清除定时器和缓存数据
    if (timer) clearInterval(timer);
    if (timer2) clearInterval(timer2);
    setObjectLocalStorage('localDataByMemory', { xDataByMemory, dataByMemory });
    setObjectLocalStorage('localDataByCpu', { xDataByCpu, dataByCpu });
  });
</script>

<style scoped lang="less">
  .home-page {
    padding: 8px;
  }

  .p-4-tag {
    width: 100%;
    height: 100%;
    //background-color: #fff;

    .descriptions-style {
      margin-bottom: 20px;
    }

    ::v-deep .ant-descriptions-small .ant-descriptions-row > td {
      padding-bottom: 0;
    }

    ::v-deep .ant-card-head-title {
      font-size: 16px;
      font-weight: 800;
      position: relative;
    }

    .page-container {
      background-color: #fff;
      margin-bottom: 7px;
    }

    .flex-row {
      display: flex;
      flex-direction: row;
    }

    .card-text {
      font-size: 12px;
      color: #909399;
    }

    .card-ul {
      display: flex;
      margin-bottom: 0;
    }

    .card-ul li {
      height: 80px;
      float: left;
      width: 18%;
      margin-right: 20px;
      display: flex;
      flex: 1;
      color: #fff;
    }

    .card-ul li:last-child {
      margin-right: 0;
    }

    .li-icon {
      display: inline-flex;
      align-items: center;
      padding: 0 20px;
    }

    .li-svg {
      position: relative;
      top: 16px;
      margin: 0 15px;
    }

    .color-red {
      background-color: #fa3534;
    }

    .color-green {
      background-color: #19be6b;
    }

    .color-yellow {
      background-color: #ff9900;
    }

    .color-blue {
      background-color: #2979ff;
    }

    .color-purple {
      background-color: #993399;
    }

    .li-text {
      font-size: 16px;
      font-weight: 700;
      padding-left: 10px;
    }

    .potion-re {
      position: relative;
      top: 12px;
    }

    .font-32 {
      font-size: 26px;
      font-weight: 700;
      position: relative;
      top: -11px;
    }

    .conter-left {
      width: 40%;
      margin-right: 8px;
      height: 500px;
      overflow: hidden;
      overflow-y: scroll;
    }

    .shortcuts-ul {
      display: flex;
      margin-bottom: 0;
    }

    .shortcuts-ul > li {
      width: 33.3%;
      height: 120px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .shortcuts-ul > li > p {
      color: #82848a;
      padding-top: 15px;
      font-size: 15px;
      margin-bottom: 0;
    }

    .title-description {
      position: absolute;
      font-size: 12px;
      color: #909399;
      top: 15px;
      left: 81px;
    }

    .echarts-list {
      display: flex;
      flex-wrap: wrap;
    }

    .echarts-list > li {
      // flex: 1;
      // border: 1px solid;
      display: flex;
      width: 50%;
      flex-direction: column;
      align-items: center;
      padding: 10px 0;
    }

    .echarts-li-title {
      font-size: 17px;
      color: #909399;
    }

    .echarts-li-value {
      font-size: 14px;
      color: #909399;
      margin-top: 8px;
    }

    ::v-deep .ant-tabs-large > .ant-tabs-nav .ant-tabs-tab {
      padding: 8px 0;
    }
  }
</style>
